package com.kgc.storeconsumer.controller;

import com.kgc.basic.util.ResponseMsg;
import com.kgc.store.pojo.InStore;
import com.kgc.storeconsumer.feign.CostAdjustmentFeign;
import com.kgc.storeconsumer.feign.ImportExportFeign;
import com.kgc.storeconsumer.feign.InStoreFeign;
import com.kgc.storeconsumer.feign.InStoreWorkFlowFeign;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.Base64;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Controller
@CrossOrigin("*")
@RequestMapping("/inStore")
public class InStoreController {
    private Logger logger = LoggerFactory.getLogger(getClass());
    @Autowired
    private InStoreFeign inStoreFeign;

    @Autowired
    private ImportExportFeign importExportFeign;

    @Autowired
    private InStoreWorkFlowFeign inStoreWorkFlowFeign;



    //导入
    @RequestMapping(value = "/import", method = RequestMethod.POST, consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public ResponseMsg importInfo(@RequestPart("file") MultipartFile file) {
        logger.info("consumer CustomerController importInfo fileName:{}", file.getOriginalFilename());
        return importExportFeign.importInfo(file, "com.kgc.store.pojo.InStore", "code", "");
    }

    //下载模板
    @RequestMapping(value = "/template", method = RequestMethod.GET)
    public void downTemplate(HttpServletResponse response) {
        logger.info("consumer CustomerController downTemplate is start...");
        try {
            ResponseMsg responseMsg = importExportFeign.downLoadTemplate("com.kgc.store.pojo.InStore");
            if ("200".equals(responseMsg.getCode())) {
                String base64Data = (String) responseMsg.getData();
                byte[] templateData = Base64.getDecoder().decode(base64Data);   //解码

                //设置响应头
                response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
                response.setCharacterEncoding("UTF-8");
                String filename = URLEncoder.encode("客户信息表.xlsx", "UTF-8");
                response.setHeader("Content-Disposition", "attachment; filename=" + filename);

                response.getOutputStream().write(templateData);
            } else {
                logger.error("下载模板失败, status: {}", responseMsg.getMsg());
                response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            }
        } catch (IOException e) {
            logger.error("consumer CustomerController downTemplate is error", e);
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }
    }

    @RequestMapping(value = "/export")
    public void exportSalesInvoices(@RequestBody Map<String, Object> map, HttpServletResponse response) {
        logger.info("consumer SalesInvoiceController exportSalesInvoices params:{}", map);
        try {
            ResponseMsg responseMsg = importExportFeign.exportEntities(map, "com.kgc.store.pojo.InStore", "create_date desc");
            if ("200".equals(responseMsg.getCode())) {
                String base64Data = (String) responseMsg.getData();
                byte[] exportData = Base64.getDecoder().decode(base64Data);

                //设置响应头
                response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
                response.setCharacterEncoding("UTF-8");
                String filename = URLEncoder.encode("销售退货单信息表.xlsx", "UTF-8");
                response.setHeader("Content-Disposition", "attachment; filename=" + filename);

                response.getOutputStream().write(exportData);
            } else {
                logger.error("导出失败, msg: {}", responseMsg.getMsg());
                response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            }
        } catch (IOException e) {
            logger.error("consumer SalesInvoiceController exportSalesInvoices is error", e);
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }
    }


    @RequestMapping("getInStoreList")
    @ResponseBody
    public ResponseMsg getInStoreList(@RequestBody Map<String, Object> map){
        logger.info("InStoreController getInStoreList map:"+map);
        ResponseMsg msg =inStoreFeign.getInStoreList(map);
        logger.debug("InStoreController getInStoreList msg:"+msg);
        return msg;
    }

    @RequestMapping("delInStore")
    @ResponseBody
    public ResponseMsg delInStore(Integer id){
        logger.info("InStoreController delInStore id:"+id);
        ResponseMsg msg =inStoreFeign.delInStore(id);
        logger.debug("InStoreController delInStore msg:"+msg);
        return msg;
    }

    @RequestMapping("addInStore")
    @ResponseBody
    ResponseMsg addInStore(@RequestBody InStore inStore){
        logger.info("InStoreController addInStore inStore:"+inStore);
        ResponseMsg msg =inStoreFeign.addInStore(inStore);
        logger.debug("InStoreController addInStore msg:"+msg);
        return msg;
    }

    @RequestMapping("getInStoreByCode")
    @ResponseBody
    ResponseMsg getInStoreByCode(String code){
        logger.info("InStoreController getInStoreByCode code:"+code);
        ResponseMsg msg =inStoreFeign.getInStoreByCode(code);
        logger.debug("InStoreController getInStoreByCode msg:"+msg);
        return msg;
    }

    @RequestMapping("check")
    @ResponseBody
    ResponseMsg check(@RequestBody Map<String,Object> map){
        ResponseMsg responseMsg = new ResponseMsg();
        logger.info("SalesOrdersController check params,{}",map.toString());
        Map<String,Object> variables = new HashMap<>();
        variables.put("code",(String) map.get("code"));//单据编号
        variables.put("checkManId",(Integer) map.get("checkManId"));//审批人
        variables.put("checkManName",(String) map.get("checkManName"));//审批人
        variables.put("checkComment",(String) map.get("checkComment"));//审批意见
        variables.put("checkDate",new Date());//审批时间
        variables.put("checkRes",(boolean)map.get("checkRes"));//审批结果
        com.kgc.activiti.util.ResponseMsg msg=  inStoreWorkFlowFeign.competeTask(variables);
        responseMsg.setCode(msg.getCode());
        responseMsg.setMsg(msg.getMsg());
        return responseMsg;
    }
}
